package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.entity.SpecGroup;

import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import com.leyou.user.dto.SpecGroupDTO;
import com.leyou.user.dto.SpecParamDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        List<SpecGroup> groupList = this.query().eq("category_id", categoryId).list();
        if(CollectionUtils.isEmpty(groupList)){
            throw new LyException(404, "该分类下的规格组不存在！");
        }
        List<SpecParam> paramList = paramService.queryParams(null, categoryId, null);
        List<SpecParamDTO> specParamDTOs = BeanHelper.copyWithCollection(paramList, SpecParamDTO.class);
        Map<Long, List<SpecParamDTO>> map = specParamDTOs.stream().collect(Collectors.groupingBy(SpecParamDTO::getCategoryId));
        List<SpecGroupDTO> specGroupDTOs = BeanHelper.copyWithCollection(groupList, SpecGroupDTO.class);
        for (SpecGroupDTO groupDTO : specGroupDTOs) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return specGroupDTOs;
    }
}